package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.bo.MailInfoBO;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.mq.MailProducer;
import com.mall.user.utils.AESUtil;
import com.mall.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender mailSender;

    @Autowired
    MailProducer producer;

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = null;
        try {
            response = new UserRegisterResponse();
            registerRequest.requestCheck();

            //验证用户名及邮箱是否重复
            volidUserNameRepeat(registerRequest);
            //向用户表中出入入一条数据
            Member member = new Member();
            member.setUsername(registerRequest.getUserName());
            member.setEmail(registerRequest.getEmail());
//        String password = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
            //密码加密
            String password = new AESUtil(registerRequest.getUserPwd()).encrypt();
            member.setPassword(password);
            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setIsVerified("N");
            member.setState(1);

            int effectRows = memberMapper.insert(member);
            if (effectRows != 1) {
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }

            //向用户验证表中插入一条数据
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());
            String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");
            int rows = userVerifyMapper.insert(userVerify);
            if (rows != 1) {
                response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }


            //消息中间件MQ发送邮件
//        sendEmail(uuid, registerRequest);

            //使用消息中间件完成
            MailInfoBO mailInfoBO = new MailInfoBO();
            mailInfoBO.setUuid(uuid);
            mailInfoBO.setUserRegisterRequest(registerRequest);
            producer.sendMailMessage(mailInfoBO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("com.mall.user.services.RegisterServiceImpl.register occurs error: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            return response;
        }

        log.info("用户注册成功,注册参数request:{}", JSON.toJSONString(registerRequest));
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

   /* //发送用户激活邮件
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("CSMALL用户激活");
            message.setFrom("ciggarnot@163.com");
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("http://localhost:8080/user/verify?uid=").append(uuid).append("&username=")
                    .append(registerRequest.getUserName());
            message.setText(stringBuilder.toString());
            mailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
            log.info("com.mall.user.services.RegisterServiceImpl occur exception:" + e);
        }
    }*/

    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {
        //邮箱重复判断
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("email", registerRequest.getEmail());
        List<Member> members = memberMapper.selectByExample(memberExample);

        //邮箱重复
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getCode(),
                    SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getMessage());
        }

        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", registerRequest.getUserName());
        List<Member> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            //用户名重复
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),
                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
